package com.wq.httpclientcore.utils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PlaceholderResolver {

    private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{(.*?)\\}");

    /**
     * 解析占位符并替换为实际值
     * @param template 包含占位符的模板字符串
     * @param values 占位符对应的值
     * @return 替换后的字符串
     */
    public static String resolve(String template, Map<String, Object> values) {
        if (template == null || template.isEmpty()) {
            return template;
        }

        Matcher matcher = PLACEHOLDER_PATTERN.matcher(template);
        StringBuilder resolved = new StringBuilder();
        while (matcher.find()) {
            String placeholder = matcher.group(1); // 获取占位符名称
            Object value = values.get(placeholder); // 获取对应的值
            if (value != null) {
                matcher.appendReplacement(resolved, value.toString()); // 替换占位符
            } else {
                matcher.appendReplacement(resolved, ""); // 如果值为空，替换为空字符串
            }
        }
        matcher.appendTail(resolved);
        return resolved.toString();
    }
}